
// 1. 实现连缀调用
// Person('people').eat('banner').sleep(3000).eat('apple').sleepFirst(4000).eat('梨')
// 以此调用为例最终的结果为：打印台先等待4S（sleepFirst的作用）,然后打印this is people，然后打印‘吃香蕉’，然后等待3S（sleep的作用），再打印‘吃apple’，最后打印‘吃梨’

// // 只要在链式中出现sleepFirst那就得先执行它--> 让整个执行程序先‘沉睡’
let index = 0
let stack = []
function next(){
    let fun = stack[index]
    index++
    if(typeof(fun)==='function'){
        fun()
    }
}
function Man(name){
    stack.push(function(){
        console.log(name);
        next()
    })
}
function Person(name){
    return new Man(name)
}
Man.prototype.eat = function(a){
    stack.push(function(){
        console.log(a);
        next()
        
    })
    return this
}
Man.prototype.sleep = function(a){
    stack.push(function(){
        setTimeout(()=>{
            next()
        },a)
    })
    return this
}
Man.prototype.sleepFirst = function(a){
    stack.unshift(function(){
        setTimeout(()=>{
            next()
        },a)
    })
    return this
}
Person('people').eat('banner').sleep(3000).eat('apple').sleepFirst(4000).eat('梨')
next()

// 2. 补全代码


function getNumber(time) {
    // 在time时间之后生成一个1-100之间的随机数，并返回
    return new Promise((res,rej)=>{
        setTimeout(()=>{
            let a = Math.floor(Math.random() * (100 - 1)) + 1
            res(a)
        },time)
    })
}

function* reducerNumber() {
    const number_1 = yield getNumber(300); 
    const number_2 = yield getNumber(300); 
    const number_3 = yield getNumber(300); 
    const number_4 = yield getNumber(300); 
    return number_4
}


const o = reducerNumber();

function run(o,sum) {
    // your codes
    return new Promise((res,rej)=>{
        o.next().value.then(res=>{
            console.log(res);
            
            sum+=res
        })
        
        o.next().value.then(res=>{
            console.log(res);
            
            sum+=res
        })
        
        o.next().value.then(res=>{
            console.log(res);
            
            sum+=res
        })
        
        o.next().value.then(res=>{
            console.log(res);
            
            sum+=res
        })
    })
    
    
};


// 该方法最终返回number_1 -- number_4的和
run(o,0);




